package GameServer.net;

import GameServer.Demo;
import GameServer.core.GameInit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by gzhd on 2017/11/29.
 */
public class NetFramework {


    private NetHandler handler;
    private String ip;
    private int port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static NetFramework inst;
    public static BlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
    JSONObject exit = new JSONObject();

    private NetFramework(String ip, int port) {
        this.setIp(ip);
        this.setPort(port);
        inst = this;
    }

    public static NetFramework buildNetFramework(String ip, int port) {
        return new NetFramework(ip, port);
    }

    public void start() throws Exception {
        Demo.print("net start success");
        reading();
    }

    public void shut() throws Exception {
        Demo.print("net shut sucess");
        queue.add(exit);
    }

    private void reading() {
        System.out.println("开启读线程");
        Thread readingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (GameInit.state == 1) {
                    System.out.println("进入循环``````");
                    JSONObject msg = null;
                    try {
                        System.out.println("进入等待队列---等待中````有消息插入马上响应``");
                        msg = queue.take();
                        System.out.println("从队列拿出来！");
                    } catch (InterruptedException e) {
                        Demo.print("Except");
                        continue;
                    }
                    if (msg == exit) {
                        break;
                    }

                    try {
                        if (handler == null) {
                            throw new Exception("handler is not setted");
                        }
                        handler.read(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("退出循环``````");
                }

                Demo.print("关闭网络模块");
            }
        }, "NetFramework");
        readingThread.start();
    }

    public void setHandler(NetHandler handler) {
        this.handler = handler;
    }

    public void write(JSON request) {
        if (handler == null) {
            Demo.print("handler is not set");
            return;
        }
        handler.write(request);
    }


}
